package com.itheima.provider.controller;

import com.itheima.provider.domain.Goods;
import com.itheima.provider.service.GoodsService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * Goods Controller 服务提供方
 */

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Value("${server.port}")
    private int port;


    /*
    降级
    1.出现异常
    2.超时   *默认为1s
    @HystrixCommand(fallbackMethod = "findOne_fallback")
    fallbackMethod：指定降级后调用的方法名称
     */
    @GetMapping("/findOne/{id}")
    @HystrixCommand(fallbackMethod = "findOneFallback",
            commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")})
    public Goods findOne(@PathVariable("id") int id) {

        Goods goods = goodsService.findOne(id);

      /*  if (id == 1) {
            //1.出现异常导致的降级
            int i = 1 / 0;
        }*/

        //2.超时出现的异常
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        goods.setTitle(goods.getTitle() + ":" + port);//将端口号，设置到了 商品标题上
        return goods;
    }

    /*
    定义降级方法
    1.方法的返回值需要和原方法一样
    2.方法的参数需要和原方法一样
    3.就是只有方法名不同
     */
    public Goods findOneFallback(int id) {
        Goods goods = new Goods();
        goods.setTitle("服务提供者降级了~~~");
        return goods;
    }
}
